package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private WorkspaceService workspaceService;

    //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
//    private String dateList;

    //营业额，以逗号分隔，例如：406.0,1520.0,75.0
//    private String turnoverList;
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //begin to end 的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(+1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate dateTime : dateList) {
            //select sum(amount) from orders where order_time > ? and order_time < ? and status = 5
            LocalDateTime beginTime = LocalDateTime.of(dateTime, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(dateTime,LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            Double sumAmount = orderMapper.sumAmount(beginTime,endTime,status);
            sumAmount = sumAmount==null? 0.0:sumAmount;
            turnoverList.add(sumAmount);
        }


        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        //private String dateList;

        //用户总量，以逗号分隔，例如：200,210,220
        //private String totalUserList;

        //新增用户，以逗号分隔，例如：20,21,10
        //private String newUserList;
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        //将日期天数添加到list中
        while (!begin.equals(end)){
            begin = begin.plusDays(+1);
            dateList.add(begin);
        }

        List<Long> totalUserList = new ArrayList<>();
        List<Long> newUserList = new ArrayList<>();
        //查询用户总量 截至目标天数的用户人数
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            //select count(id) from user where create_time < ?
            Long totalUser = userMapper.sumUsers(null,endTime);
            Long newUser = userMapper.sumUsers(beginTime, endTime);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }

    @Override
//    @Cacheable(cacheNames = "ordersStatistics",key = "#begin")
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        //private String dateList;

        //每日订单数，以逗号分隔，例如：260,210,215
        //private String orderCountList;

        //每日有效订单数，以逗号分隔，例如：20,21,10
        //private String validOrderCountList;

        //订单总数
        //private Integer totalOrderCount;

        //有效订单数
        //private Integer validOrderCount;

        //订单完成率
        //private Double orderCompletionRate;
        List<LocalDate> dateList = new ArrayList<>();
        Integer status = Orders.COMPLETED;
        Double orderCompletionRate = 0.0;

        dateList.add(begin);

        //将日期天数添加到list中
        while (!begin.equals(end)){
            begin = begin.plusDays(+1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        //查询订单总量 有效订单量
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            //select count(id) from user where create_time < ? and status = 5
            Integer orderCount = userMapper.sumOrder(beginTime,endTime,null);
            Integer validOrder = userMapper.sumOrder(beginTime, endTime, status);

            totalOrderCount+=orderCount;
            validOrderCount+=validOrder;

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }
        if(totalOrderCount!=0) {
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }

        return OrderReportVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //商品名称列表，以逗号分隔，例如：鱼香肉丝,宫保鸡丁,水煮鱼
        //private String nameList;

        //销量列表，以逗号分隔，例如：260,215,200
        //private String numberList;
        Integer status = Orders.COMPLETED;
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        //将日期天数添加到list中
        while (!begin.equals(end)){
            begin = begin.plusDays(+1);
            dateList.add(begin);
        }

        //查询菜品和套餐销量
        //获取菜品名称列表
        List<String> nameList = new ArrayList<>();
        //select count(id) from order_detail where name = ?
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> salesCount = orderDetailMapper.getSalesCount(beginTime, endTime, status);
        nameList = salesCount.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        numberList = salesCount.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();

    }

    @Override
    public void export(HttpServletResponse httpServletResponse) {
        //查询数据库获得最近三十天运营数据
        LocalDate begin = LocalDate.now().plusDays(-30);
        LocalDate end = LocalDate.now().plusDays(-1);
        //概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //通过poi将数据写入excel中
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //创建新的excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //填充数据
            XSSFSheet sheet = excel.getSheet("sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间"+begin+"至"+end);
            XSSFRow row3 = sheet.getRow(3);
            row3.getCell(2).setCellValue(businessDataVO.getTurnover());
            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row3.getCell(6).setCellValue(businessDataVO.getNewUsers());

            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate days = begin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(days, LocalTime.MIN), LocalDateTime.of(days, LocalTime.MAX));
                XSSFRow row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(days.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流将文件下载到浏览器中
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);

            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
